package com.example.dense_rack_server.controller.dataBackup;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.dense_rack_server.entity.BackupLog;
import com.example.dense_rack_server.entity.BackupTask;
import com.example.dense_rack_server.entity.SysParamset;
import com.example.dense_rack_server.mapper.SysParamsetMapper;
import com.example.dense_rack_server.mapper.dataBackup.BackupTaskMapper;
import com.example.dense_rack_server.service.dataBackup.BackupLogService;
import com.example.dense_rack_server.service.dataBackup.NodeInfoService;
import com.example.dense_rack_server.utils.DataBackup.SqlFileExecutor;
import com.example.dense_rack_server.utils.DataBackup.quartz.QuartzManager;
import com.example.dense_rack_server.utils.ResponseModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.io.File;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 备份记录 前端控制器
 * </p>
 *
 * @author  张彬 
 * @since 2025-07-01
 */
@Slf4j
@Controller
@RequestMapping("/backup/backup/log")
public class BackupLogController {

    @Resource
    private BackupLogService backupLogService;
    @Resource
    private NodeInfoService nodeInfoService;
    @Value("${SavePath.nginxPath}")
    private String nginxPath;
    @Resource
    private SysParamsetMapper sysParamsetMapper;
    @Resource
    private SqlFileExecutor sqlFileExecutor;
    @Resource
    public BackupTaskMapper backupTaskMapper;
    @Resource
    private QuartzManager quartzManager;
    @Autowired
    DataSource dataSource;

    /**
     * 备份记录首页
     */
    @GetMapping("index")
    public ModelAndView list() {
        ModelAndView modelAndView = new ModelAndView("DataBackup/backupLog/index");
        modelAndView.addObject("node", nodeInfoService.list(null));
        modelAndView.addObject("nginxPath", nginxPath);
        return modelAndView;
    }



    /**
     * 备份记录分页查询
     */
    @GetMapping("list")
    @ResponseBody
    public Map<String, Object> tableList(@RequestParam(value = "nodeId", required = false) String nodeId,
                                         @RequestParam(value = "category", required = false) String category,
                                         @RequestParam(value = "status", required = false) String status,
                                         @RequestParam(value = "databaseName", required = false) String databaseName,
                                         @RequestParam(value = "tablesName", required = false) String tablesName,
                                         @RequestParam(value = "page") int page,
                                         @RequestParam(value = "limit") int limit) {
        return backupLogService.tableList(page, limit, nodeId, category, status, databaseName, tablesName);
    }


    /**
     * 备份记录恢复
     */
    @GetMapping("/importsql")
    @ResponseBody
    public ResponseModel importSql(@RequestParam(value = "id") String id) {
        try {
            SysParamset sysParamset = sysParamsetMapper.selectById(1);
            String paramValue = sysParamset.getParamValue();
            BackupLog backupLog = backupLogService.getById(id);
            String filePath = paramValue + File.separator + backupLog.getFilePath();

            List<BackupTask> list = backupTaskMapper.selectList(new QueryWrapper<BackupTask>().eq("status", true));
            for (BackupTask backupTask : list) {
                quartzManager.stop(backupTask.getId());
            }
            Thread.sleep(100);
            File file = new File(filePath);
            if (!file.exists()) {
                return ResponseModel.fail("文件不存在");
            }
            sqlFileExecutor.executeSqlFile(filePath);
            Thread.sleep(100);
            for (BackupTask backupTask : list) {
                quartzManager.start(backupTask.getId());
            }

            // 另一种办法 因为sql 文件中LOCK TABLES语句 不能使用
//            log.info("数据初始化开始: " + DateFormat.getTime());
//            ResourceDatabasePopulator resourceDatabasePopulator = new ResourceDatabasePopulator();
//            ResourceDatabasePopulator resourceDatabasePopulator = new ResourceDatabasePopulator();
//            resourceDatabasePopulator.addScript(new FileSystemResource(filePath));
//            resourceDatabasePopulator.execute(dataSource);
//            log.info("数据初始化结束: " + DateFormat.getTime());
            return ResponseModel.success("导入成功");
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseModel.fail("导入失败");
        }
    }

}
